<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>物联网可视化平台 - Event Engine 测试页面</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
            color: #333;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
        }

        .header p {
            font-size: 1.1rem;
            opacity: 0.9;
        }

        .main-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            padding: 30px;
        }

        .test-section {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            border-left: 4px solid #007bff;
        }

        .test-section h3 {
            color: #007bff;
            margin-bottom: 15px;
            font-size: 1.3rem;
            display: flex;
            align-items: center;
        }

        .test-section h3::before {
            content: "🔧";
            margin-right: 10px;
        }

        .button-group {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 20px;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 0.9rem;
            font-weight: 500;
            transition: all 0.3s ease;
            flex: 1;
            min-width: 120px;
        }

        .btn-primary {
            background: #007bff;
            color: white;
        }

        .btn-primary:hover {
            background: #0056b3;
            transform: translateY(-2px);
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-success:hover {
            background: #1e7e34;
        }

        .btn-warning {
            background: #ffc107;
            color: #212529;
        }

        .btn-warning:hover {
            background: #e0a800;
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn-danger:hover {
            background: #c82333;
        }

        .log-container {
            grid-column: span 2;
            background: #1e1e1e;
            color: #f8f8f2;
            border-radius: 10px;
            padding: 20px;
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
            font-size: 0.9rem;
            line-height: 1.4;
            max-height: 400px;
            overflow-y: auto;
            border: 2px solid #333;
        }

        .log-entry {
            margin-bottom: 8px;
            padding: 5px 10px;
            border-radius: 4px;
            animation: fadeIn 0.3s ease-in;
        }

        .log-info {
            background: rgba(0, 123, 255, 0.1);
            border-left: 3px solid #007bff;
        }

        .log-success {
            background: rgba(40, 167, 69, 0.1);
            border-left: 3px solid #28a745;
        }

        .log-warning {
            background: rgba(255, 193, 7, 0.1);
            border-left: 3px solid #ffc107;
            color: #fff3cd;
        }

        .log-error {
            background: rgba(220, 53, 69, 0.1);
            border-left: 3px solid #dc3545;
            color: #f8d7da;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }

        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            border-top: 3px solid #007bff;
        }

        .stat-value {
            font-size: 2rem;
            font-weight: bold;
            color: #007bff;
            display: block;
        }

        .stat-label {
            color: #666;
            font-size: 0.9rem;
            margin-top: 5px;
        }

        .controls {
            grid-column: span 2;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
        }

        .controls h3 {
            margin-bottom: 15px;
        }

        .clear-btn {
            background: rgba(255, 255, 255, 0.2);
            border: 2px solid rgba(255, 255, 255, 0.3);
            color: white;
            padding: 10px 30px;
            border-radius: 25px;
            cursor: pointer;
            font-size: 1rem;
            transition: all 0.3s ease;
        }

        .clear-btn:hover {
            background: rgba(255, 255, 255, 0.3);
            border-color: rgba(255, 255, 255, 0.5);
        }
    </style>
</head>
<body>
    <div class="container">
        <header class="header">
            <h1>🚀 Event Engine 测试中心</h1>
            <p>物联网可视化平台事件引擎完整功能测试</p>
        </header>

        <div class="main-content">
            <!-- 基础事件测试 -->
            <div class="test-section">
                <h3>基础事件测试</h3>
                <div class="button-group">
                    <button class="btn btn-primary" onclick="testBasicEvents()">基础事件发送</button>
                    <button class="btn btn-success" onclick="testEventListener()">事件监听器测试</button>
                    <button class="btn btn-warning" onclick="testEventCleanup()">清理机制测试</button>
                </div>
            </div>

            <!-- 配置事件兼容性测试 -->
            <div class="test-section">
                <h3>配置事件兼容性测试</h3>
                <div class="button-group">
                    <button class="btn btn-primary" onclick="testConfigCompatibility()">配置事件兼容</button>
                    <button class="btn btn-success" onclick="testConfigEventBus()">ConfigEventBus集成</button>
                    <button class="btn btn-warning" onclick="testDataTrigger()">数据触发器测试</button>
                </div>
            </div>

            <!-- 适配器测试 -->
            <div class="test-section">
                <h3>系统适配器测试</h3>
                <div class="button-group">
                    <button class="btn btn-primary" onclick="testCard21Adapter()">Card2.1 适配器</button>
                    <button class="btn btn-success" onclick="testVisualEditorAdapter()">Visual Editor 适配器</button>
                    <button class="btn btn-warning" onclick="testCoreAdapter()">Core 适配器</button>
                </div>
            </div>

            <!-- 性能和错误处理测试 -->
            <div class="test-section">
                <h3>性能和错误处理测试</h3>
                <div class="button-group">
                    <button class="btn btn-primary" onclick="testPerformance()">性能测试</button>
                    <button class="btn btn-danger" onclick="testErrorHandling()">错误处理测试</button>
                    <button class="btn btn-warning" onclick="testMemoryLeaks()">内存泄漏测试</button>
                </div>
            </div>

            <!-- 控制面板 -->
            <div class="controls">
                <h3>🎛️ 控制面板</h3>
                <button class="clear-btn" onclick="clearLogs()">清空日志</button>
                <button class="clear-btn" onclick="showStatistics()" style="margin-left: 15px;">显示统计</button>
            </div>

            <!-- 日志显示区域 -->
            <div class="log-container" id="logContainer">
                <div class="log-entry log-info">
                    <strong>[INFO]</strong> 🎯 Event Engine 测试页面已加载，等待测试开始...
                </div>
            </div>
        </div>
    </div>

    <script>
        // ===== 模拟 Event Engine 和相关模块 =====
        
        // 模拟 ConfigEventBus
        const mockConfigEventBus = {
            handlers: new Map(),
            statistics: {
                eventsEmitted: 0,
                handlersExecuted: 0,
                errors: 0
            },
            onConfigChange(eventType, handler) {
                if (!this.handlers.has(eventType)) {
                    this.handlers.set(eventType, new Set());
                }
                this.handlers.get(eventType).add(handler);
                log(`[ConfigEventBus] 注册配置事件监听器: ${eventType}`, 'info');
                
                return () => {
                    this.handlers.get(eventType).delete(handler);
                    log(`[ConfigEventBus] 取消配置事件监听器: ${eventType}`, 'info');
                };
            },
            async emitConfigChange(event) {
                this.statistics.eventsEmitted++;
                const handlers = this.handlers.get(event.section) || new Set();
                
                log(`[ConfigEventBus] 发出配置事件: ${event.section}`, 'success');
                log(`📋 事件详情: ${JSON.stringify(event, null, 2)}`, 'info');
                
                for (const handler of handlers) {
                    try {
                        await handler(event);
                        this.statistics.handlersExecuted++;
                    } catch (error) {
                        this.statistics.errors++;
                        log(`[ConfigEventBus] 处理器执行失败: ${error.message}`, 'error');
                    }
                }
            },
            getStatistics() {
                return { ...this.statistics };
            }
        };

        // 模拟 Event Engine
        class MockEventEngine {
            constructor() {
                this.extendedHandlers = new Map();
                this.stats = {
                    totalEvents: 0,
                    extendedEvents: 0,
                    configEvents: 0
                };
                this.cleanupFunctions = [];
            }

            // 向后兼容接口
            onConfigChange = mockConfigEventBus.onConfigChange.bind(mockConfigEventBus);
            emitConfigChange = mockConfigEventBus.emitConfigChange.bind(mockConfigEventBus);

            on(eventType, handler) {
                // 配置事件类型处理
                const configEventTypes = [
                    'config-changed', 'data-source-changed', 'component-props-changed',
                    'base-config-changed', 'interaction-changed', 'before-config-change',
                    'after-config-change'
                ];
                
                if (configEventTypes.includes(eventType)) {
                    log(`[EventEngine] 配置事件类型 ${eventType} 转发到 ConfigEventBus`, 'warning');
                    return this.onConfigChange(eventType, (configEvent) => {
                        const extendedEvent = {
                            type: eventType,
                            payload: configEvent,
                            timestamp: configEvent.timestamp,
                            source: configEvent.source,
                            componentId: configEvent.componentId
                        };
                        this.safeExecuteHandler(handler, extendedEvent);
                    });
                }

                // 扩展事件类型处理
                if (!this.extendedHandlers.has(eventType)) {
                    this.extendedHandlers.set(eventType, new Set());
                }

                this.extendedHandlers.get(eventType).add(handler);
                log(`[EventEngine] 注册扩展事件监听器: ${eventType}`, 'info');

                const cleanup = () => {
                    const handlers = this.extendedHandlers.get(eventType);
                    if (handlers) {
                        handlers.delete(handler);
                        if (handlers.size === 0) {
                            this.extendedHandlers.delete(eventType);
                        }
                    }
                    log(`[EventEngine] 清理扩展事件监听器: ${eventType}`, 'info');
                };

                this.cleanupFunctions.push(cleanup);
                return cleanup;
            }

            async emit(eventType, payload, source = 'unknown') {
                this.stats.totalEvents++;
                
                // 配置事件处理
                const configEventTypes = [
                    'config-changed', 'data-source-changed', 'component-props-changed',
                    'base-config-changed', 'interaction-changed'
                ];
                
                if (configEventTypes.includes(eventType)) {
                    if (this.isValidConfigChangeEvent(payload)) {
                        this.stats.configEvents++;
                        await mockConfigEventBus.emitConfigChange(payload);
                        return;
                    } else {
                        log(`[EventEngine] 配置事件格式不正确: ${eventType}`, 'error');
                        return;
                    }
                }

                // 扩展事件处理
                this.stats.extendedEvents++;
                const event = {
                    type: eventType,
                    payload,
                    timestamp: Date.now(),
                    source,
                    componentId: payload?.componentId
                };

                const handlers = this.extendedHandlers.get(eventType);
                if (!handlers || handlers.size === 0) {
                    log(`[EventEngine] 事件类型 ${eventType} 没有监听器`, 'warning');
                    return;
                }

                log(`[EventEngine] 发出扩展事件: ${eventType}`, 'success');
                log(`📋 事件详情: ${JSON.stringify(event, null, 2)}`, 'info');

                const promises = Array.from(handlers).map(handler => 
                    this.safeExecuteHandler(handler, event)
                );

                await Promise.allSettled(promises);
            }

            async safeExecuteHandler(handler, event) {
                try {
                    const result = handler(event);
                    if (result instanceof Promise) {
                        await result;
                    }
                    log(`✅ 事件处理器执行成功: ${event.type}`, 'success');
                } catch (error) {
                    log(`❌ 事件处理器执行失败: ${error.message}`, 'error');
                }
            }

            isValidConfigChangeEvent(payload) {
                return payload && 
                       typeof payload.componentId === 'string' &&
                       typeof payload.componentType === 'string' &&
                       typeof payload.section === 'string' &&
                       typeof payload.timestamp === 'number' &&
                       typeof payload.source === 'string';
            }

            getStatistics() {
                return {
                    ...this.stats,
                    configEventBus: mockConfigEventBus.getStatistics(),
                    activeExtendedEventTypes: this.extendedHandlers.size,
                    totalExtendedHandlers: Array.from(this.extendedHandlers.values())
                        .reduce((sum, handlers) => sum + handlers.size, 0)
                };
            }

            clear() {
                this.extendedHandlers.clear();
                this.stats = {
                    totalEvents: 0,
                    extendedEvents: 0,
                    configEvents: 0
                };
                log(`[EventEngine] 扩展事件处理器已清理`, 'info');
            }
        }

        // 创建全局实例
        const eventEngine = new MockEventEngine();
        window.eventEngine = eventEngine;

        // ===== 日志系统 =====
        function log(message, type = 'info') {
            const container = document.getElementById('logContainer');
            const entry = document.createElement('div');
            entry.className = `log-entry log-${type}`;
            
            const timestamp = new Date().toLocaleTimeString();
            const icon = {
                'info': '📘',
                'success': '✅',
                'warning': '⚠️',
                'error': '❌'
            }[type] || '📝';
            
            entry.innerHTML = `<strong>[${timestamp}]</strong> ${icon} ${message}`;
            container.appendChild(entry);
            container.scrollTop = container.scrollHeight;
        }

        function clearLogs() {
            document.getElementById('logContainer').innerHTML = '';
            log('日志已清空，准备新的测试...', 'info');
        }

        // ===== 测试函数 =====
        
        function testBasicEvents() {
            log('🧪 开始基础事件测试', 'info');
            
            // 注册事件监听器
            const cleanup = eventEngine.on('component-lifecycle', (event) => {
                log(`收到组件生命周期事件: ${event.payload.action}`, 'success');
            });

            // 发送测试事件
            eventEngine.emit('component-lifecycle', {
                componentId: 'test-component',
                action: 'created',
                timestamp: Date.now()
            }, 'test-basic');

            setTimeout(() => {
                eventEngine.emit('component-lifecycle', {
                    componentId: 'test-component',
                    action: 'destroyed',
                    timestamp: Date.now()
                }, 'test-basic');
            }, 1000);

            log('✅ 基础事件测试完成', 'success');
        }

        function testEventListener() {
            log('🧪 开始事件监听器测试', 'info');
            
            let eventCount = 0;
            const cleanup = eventEngine.on('data-update', (event) => {
                eventCount++;
                log(`数据更新事件 #${eventCount}: ${event.payload.data}`, 'success');
            });

            // 发送多个事件测试
            for (let i = 1; i <= 3; i++) {
                setTimeout(() => {
                    eventEngine.emit('data-update', {
                        data: `测试数据 ${i}`,
                        componentId: `component-${i}`
                    }, 'listener-test');
                }, i * 500);
            }

            log('✅ 事件监听器测试完成', 'success');
        }

        function testEventCleanup() {
            log('🧪 开始清理机制测试', 'info');
            
            const cleanup = eventEngine.on('ui-interaction', (event) => {
                log(`UI交互事件: ${event.payload.action}`, 'success');
            });

            // 发送事件
            eventEngine.emit('ui-interaction', {
                action: 'click',
                target: 'button'
            }, 'cleanup-test');

            // 清理监听器
            setTimeout(() => {
                cleanup();
                log('事件监听器已清理', 'warning');
                
                // 尝试再次发送事件（应该没有响应）
                eventEngine.emit('ui-interaction', {
                    action: 'click-after-cleanup',
                    target: 'button'
                }, 'cleanup-test');
                
                log('✅ 清理机制测试完成', 'success');
            }, 1500);
        }

        function testConfigCompatibility() {
            log('🧪 开始配置事件兼容性测试', 'info');
            
            // 注册配置事件监听器
            const cleanup = eventEngine.on('config-changed', (event) => {
                log(`配置变更事件: ${event.payload.section}`, 'success');
            });

            // 创建有效的配置变更事件
            const configEvent = {
                componentId: 'test-component',
                componentType: 'chart',
                section: 'dataSource',
                timestamp: Date.now(),
                source: 'user',
                oldConfig: { type: 'api' },
                newConfig: { type: 'websocket' }
            };

            // 发送配置事件
            eventEngine.emit('config-changed', configEvent, 'compat-test');
            
            log('✅ 配置事件兼容性测试完成', 'success');
        }

        function testConfigEventBus() {
            log('🧪 开始 ConfigEventBus 集成测试', 'info');
            
            // 直接使用 ConfigEventBus 方法
            const cleanup = eventEngine.onConfigChange('data-source-changed', (event) => {
                log(`ConfigEventBus 数据源变更: ${event.componentId}`, 'success');
            });

            // 创建配置事件
            const configEvent = {
                componentId: 'chart-widget',
                componentType: 'visualization',
                section: 'data-source-changed',
                timestamp: Date.now(),
                source: 'system',
                oldConfig: { url: 'old-api' },
                newConfig: { url: 'new-api' }
            };

            // 通过 EventEngine 发送
            eventEngine.emitConfigChange(configEvent);
            
            log('✅ ConfigEventBus 集成测试完成', 'success');
        }

        function testDataTrigger() {
            log('🧪 开始数据触发器测试', 'info');
            
            // 模拟数据执行触发器
            if (eventEngine.registerDataExecutionTrigger) {
                const cleanup = eventEngine.registerDataExecutionTrigger((event) => {
                    log(`数据执行触发: ${event.componentId}`, 'success');
                });

                log('数据执行触发器已注册', 'info');
            } else {
                log('数据执行触发器不可用（模拟环境）', 'warning');
            }
            
            log('✅ 数据触发器测试完成', 'success');
        }

        function testCard21Adapter() {
            log('🧪 开始 Card2.1 适配器测试', 'info');
            
            // 模拟 Card2.1 适配器
            const componentId = 'card21-test';
            const cleanup = eventEngine.on('component-lifecycle', (event) => {
                if (event.componentId === componentId) {
                    log(`Card2.1 组件事件: ${event.payload.status}`, 'success');
                }
            });

            // 发送 Card2.1 组件事件
            eventEngine.emit('component-lifecycle', {
                componentId: componentId,
                status: 'initialized',
                config: { type: 'gauge-dashboard' }
            }, 'card21-adapter');

            log('✅ Card2.1 适配器测试完成', 'success');
        }

        function testVisualEditorAdapter() {
            log('🧪 开始 Visual Editor 适配器测试', 'info');
            
            // 模拟编辑器事件
            const cleanup = eventEngine.on('ui-interaction', (event) => {
                log(`编辑器交互: ${event.payload.action}`, 'success');
            });

            // 发送编辑器事件
            eventEngine.emit('ui-interaction', {
                action: 'component-selected',
                target: 'chart-widget',
                editorMode: 'design'
            }, 'visual-editor');

            log('✅ Visual Editor 适配器测试完成', 'success');
        }

        function testCoreAdapter() {
            log('🧪 开始 Core 适配器测试', 'info');
            
            // 模拟系统事件
            const cleanup = eventEngine.on('system-ready', (event) => {
                log(`系统就绪事件: ${event.payload.module}`, 'success');
            });

            // 发送系统事件
            eventEngine.emit('system-ready', {
                module: 'data-architecture',
                version: '2.1.0',
                initTime: Date.now() - 1000
            }, 'core-adapter');

            log('✅ Core 适配器测试完成', 'success');
        }

        function testPerformance() {
            log('🧪 开始性能测试', 'info');
            
            const startTime = Date.now();
            const eventCount = 100;
            let receivedCount = 0;

            const cleanup = eventEngine.on('performance-test', (event) => {
                receivedCount++;
                if (receivedCount === eventCount) {
                    const endTime = Date.now();
                    const duration = endTime - startTime;
                    const eventsPerSecond = Math.round((eventCount / duration) * 1000);
                    log(`📊 性能测试结果: ${eventCount} 个事件，耗时 ${duration}ms，速度 ${eventsPerSecond} 事件/秒`, 'success');
                }
            });

            // 批量发送事件
            for (let i = 0; i < eventCount; i++) {
                eventEngine.emit('performance-test', {
                    index: i,
                    timestamp: Date.now()
                }, 'performance');
            }

            log('✅ 性能测试完成', 'success');
        }

        function testErrorHandling() {
            log('🧪 开始错误处理测试', 'info');
            
            // 注册会抛出异常的处理器
            const cleanup = eventEngine.on('error-test', (event) => {
                if (event.payload.shouldError) {
                    throw new Error('测试异常处理');
                }
                log(`正常处理器执行: ${event.payload.message}`, 'success');
            });

            // 发送会导致异常的事件
            eventEngine.emit('error-test', {
                shouldError: true,
                message: '这应该引发异常'
            }, 'error-test');

            // 发送正常事件
            setTimeout(() => {
                eventEngine.emit('error-test', {
                    shouldError: false,
                    message: '这应该正常处理'
                }, 'error-test');
            }, 500);

            log('✅ 错误处理测试完成', 'success');
        }

        function testMemoryLeaks() {
            log('🧪 开始内存泄漏测试', 'info');
            
            const cleanupFunctions = [];
            
            // 创建大量事件监听器
            for (let i = 0; i < 50; i++) {
                const cleanup = eventEngine.on('memory-test', (event) => {
                    // 模拟处理器
                });
                cleanupFunctions.push(cleanup);
            }

            log(`创建了 ${cleanupFunctions.length} 个事件监听器`, 'info');

            // 发送一些事件
            for (let i = 0; i < 10; i++) {
                eventEngine.emit('memory-test', { index: i }, 'memory-test');
            }

            // 清理所有监听器
            setTimeout(() => {
                cleanupFunctions.forEach(cleanup => cleanup());
                log(`清理了 ${cleanupFunctions.length} 个事件监听器`, 'warning');
                
                // 再次发送事件（应该没有监听器）
                eventEngine.emit('memory-test', { index: 'after-cleanup' }, 'memory-test');
                
                log('✅ 内存泄漏测试完成', 'success');
            }, 1000);
        }

        function showStatistics() {
            log('📊 显示事件引擎统计信息', 'info');
            
            const stats = eventEngine.getStatistics();
            
            log(`📈 总事件数: ${stats.totalEvents}`, 'info');
            log(`📈 扩展事件数: ${stats.extendedEvents}`, 'info');
            log(`📈 配置事件数: ${stats.configEvents}`, 'info');
            log(`📈 活跃事件类型: ${stats.activeExtendedEventTypes}`, 'info');
            log(`📈 总处理器数: ${stats.totalExtendedHandlers}`, 'info');
            
            log('📊 ConfigEventBus 统计:', 'info');
            log(`   - 已发出事件: ${stats.configEventBus.eventsEmitted}`, 'info');
            log(`   - 处理器执行次数: ${stats.configEventBus.handlersExecuted}`, 'info');
            log(`   - 错误次数: ${stats.configEventBus.errors}`, 'info');
            
            log('✅ 统计信息显示完成', 'success');
        }

        // 页面加载完成后的初始化
        window.onload = function() {
            log('🚀 Event Engine 测试页面加载完成', 'success');
            log('💡 点击上方按钮开始各种测试', 'info');
            log('🔍 所有测试结果将实时显示在此日志区域', 'info');
            
            // 显示初始统计信息
            setTimeout(() => {
                showStatistics();
            }, 500);
        };
    </script>
</body>
</html>